'use strict'

const fs = require('fs')
const url = require('url')
const path = require('path')
const http = require('http')

const root = path.resolve(process.argv[2] || '.')

const server = http.createServer((req, res) => {
  const pathname = url.parse(req.url).pathname
  const filepath = path.join(root, pathname)

  fs.stat(filepath, (err, stats) => {
    if (!err && stats.isFile()) {
      res.writeHead(200)
      fs.createReadStream(filepath).pipe(res)
    } else {
      const indexPath = path.join(root, 'index.html')

      fs.stat(indexPath, (err, stats) => {
        if (!err && stats.isFile()) {
          res.writeHead(200)
          fs.createReadStream(indexPath).pipe(res)
        } else {
          const defaultPath = path.join(root, 'default.html')

          fs.stat(defaultPath, (err, stats) => {
            if (!err && stats.isFile()) {
              res.writeHead(200)
              fs.createReadStream(defaultPath).pipe(res)
            } else {
              res.writeHead(404)
              res.end('404 Not Found')
            }
          })
        }
      })

    }
  })
})

server.listen(8080)